package com.wcgksoft.controller.Patrol;

import com.wcgksoft.common.util.FileHandleUtil;
import com.wcgksoft.common.util.Layui;
import com.wcgksoft.common.util.comm.StringUtils;
import com.wcgksoft.entity.ConstructionTeam.ConstructionTeam;
import com.wcgksoft.entity.GreedLand.GreedLand;
import com.wcgksoft.entity.Patrol.CompletePatrolImage;
import com.wcgksoft.entity.Patrol.PatrolAccount;
import com.wcgksoft.entity.Patrol.PatrolImage;
import com.wcgksoft.entity.system.EnterpriseProject;
import com.wcgksoft.entity.system.SysUser;
import com.wcgksoft.service.ConstructionTeam.ConstructionTeamService;
import com.wcgksoft.service.GreedLand.GreedlandService;
import com.wcgksoft.service.Patrol.CompletePatrolImageService;
import com.wcgksoft.service.Patrol.PatrolAccountService;
import com.wcgksoft.service.Patrol.PatrolImageService;
import com.wcgksoft.service.openAccount.OpenAccountService;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @ClassName PatrolAccountController
 * @Description 巡查台账
 * @Author 王宁
 * @Date 2020/3/17 13:07
 * @Version 1.0
 **/
@Controller
@RequestMapping("patrol")
public class PatrolAccountController {
    @Autowired
    private PatrolAccountService patrolAccountService;

    @Autowired
    private ConstructionTeamService constructionTeamService;

    @Autowired
    private PatrolImageService patrolImageService;

    @Autowired
    private GreedlandService greedlandService;


    @Autowired
    private OpenAccountService openAccountService;

    @Autowired
    private CompletePatrolImageService completePatrolImageService;

    /**
     * 查询所有施工团队
     *
     * @param eId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "findAllTeam")
    public Layui findAll(@RequestParam(value = "id", required = false) Integer eId) {
        DetachedCriteria criteria = DetachedCriteria.forClass(ConstructionTeam.class);
        criteria.add(Restrictions.eq("e_id", eId));
        criteria.add(Restrictions.eq("t_state", 0));
        List<ConstructionTeam> byConditions = constructionTeamService.findByConditions(criteria);
        return Layui.data(0, "查询成功", constructionTeamService.getTotalCount(), byConditions);
    }


    /**
     * 根据任务名称，问题情况查询，完成情况，施工人员
     * @param page
     * @param limit
     * @param keyWord
     * @param keyWordTwo
     * @return
     */
    @ResponseBody
    @RequestMapping("findAll")
    public Layui findAllPatrol(@RequestParam(value = "page", required = false) Integer page,
                               @RequestParam(value = "limit", required = false) Integer limit,
                               @RequestParam(value = "keyWord",required = false)String keyWord,
                               @RequestParam(value = "keyWordTwo",required = false)String keyWordTwo,
                               @RequestParam(value = "state",required = false)String state,
                               @RequestParam(value = "receiver",required = false)String receiver,
                               @RequestParam(value = "areaId",required = false)String areaId
                               ) {
        int anInt = Integer.parseInt(areaId);
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        DetachedCriteria criteria = DetachedCriteria.forClass(PatrolAccount.class);
        criteria.add(Restrictions.eq("enterpriseId", sysUser.getEnterprise().getId()));
        criteria.add(Restrictions.eq("areaId",anInt));
        if(StringUtils.isNotEmpty(keyWord)){
            criteria.add(Restrictions.like("source", keyWord, MatchMode.ANYWHERE));
        }
        if(StringUtils.isNotEmpty(state)){
            criteria.add(Restrictions.like("status", state, MatchMode.ANYWHERE));
        }
        if(StringUtils.isNotEmpty(keyWordTwo)){
            criteria.add(Restrictions.like("situation", keyWordTwo, MatchMode.ANYWHERE));
        }
        if(StringUtils.isNotEmpty(receiver)){
            criteria.add(Restrictions.like("receiverId", receiver, MatchMode.ANYWHERE));
        }
        List<PatrolAccount> list = patrolAccountService.findByConditions(criteria, page, limit);
        for (PatrolAccount patrolAccount : list) {
            DetachedCriteria criteria1 = DetachedCriteria.forClass(PatrolImage.class);
            criteria1.add(Restrictions.eq("urisid",patrolAccount.getUrisId()));
            criteria1.add(Restrictions.eq("pactrolId",patrolAccount.getId()));
            List<PatrolImage> byConditions = patrolImageService.findByConditions(criteria1);
            patrolAccount.setPatrolImages(byConditions);
        }
        for (PatrolAccount patrolAccount : list) {
            DetachedCriteria criteria2 = DetachedCriteria.forClass(CompletePatrolImage.class);
            criteria2.add(Restrictions.eq("urisid",patrolAccount.getUrisId()));
            criteria2.add(Restrictions.eq("pactrolId",patrolAccount.getId()));
            List<CompletePatrolImage> byConditions = completePatrolImageService.findByConditions(criteria2);
            patrolAccount.setCompletePatrolImageList(byConditions);
        }
        return Layui.data(0, "查询成功", patrolAccountService.getTotalCount(), list);
    }
    /**
     * 添加巡查台账
     * @param request
     * @param data
     * @param
     * @return
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "save")
    public Layui save(
            HttpServletRequest request,
            @RequestParam(value = "data", required = false) String data,
            @RequestParam(value = "file",required = false)MultipartFile[] file) throws IOException, ParseException {
        JSONObject param = JSONObject.fromObject(data);
        if (param == null) {
            return Layui.data(1, "请求格式有误", 0, null);
        } else {
            PatrolAccount patrolAccount = (PatrolAccount) JSONObject.toBean(JSONObject.fromObject(data), PatrolAccount.class);
            SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");

            String revId = (String) param.get("receiverId");
            Integer rid = Integer.parseInt(revId);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String grId = (String) param.get("greenId");
            Integer gid = Integer.parseInt(grId);
            GreedLand byId1 = greedlandService.findById(gid);
            patrolAccount.setGreenName(byId1.getGreedLandAdministrator().getName());
            String completeTime = (String) param.get("completeTime");
            patrolAccount.setCompleteTime(simpleDateFormat.parse(completeTime));
            //绿地ID
            patrolAccount.setUrisId(gid);
            //施工队信息
            SysUser byId = openAccountService.findById(rid);
            patrolAccount.setReceiver(byId.getName());
            //项目id
            patrolAccount.setProId(sysUser.getProId());
            //发布时间
            patrolAccount.setPublishTime(new Date());
            //状态未完成
            patrolAccount.setStatus("2");
            patrolAccountService.saveOrUpdate(patrolAccount);
            for (MultipartFile mf : file) {
                PatrolImage patrolImage = new PatrolImage();
                if (!mf.isEmpty()) {
                    String filename = FileHandleUtil.Upset(mf);
                    patrolImage.setImage("upload/picture/" + FileHandleUtil.upload(mf.getInputStream(), "upload/picture/", filename, request));
                    patrolImage.setUrisid(gid);
                    patrolImage.setConstructionTeamId(rid);
                    patrolImage.setPactrolId(patrolAccount.getId());
                    patrolImageService.saveOrUpdate(patrolImage);
                }
            }
            return Layui.data(0, "操作成功", patrolAccountService.getTotalCount(), Layui.addList(patrolAccount));
        }
    }

    /**
     * 删除巡查台账
     */
    @ResponseBody
    @RequestMapping(value = "delete")
    public Layui delete(@RequestParam(value = "id",required = false)Integer id){
        PatrolAccount byId = patrolAccountService.findById(id);
        patrolAccountService.delete(byId);
        return Layui.data(0, "删除成功", Layui.addList(byId));
    }

    @ResponseBody
    @RequestMapping(value = "list")
    public Layui list() {
        DetachedCriteria criteria = DetachedCriteria.forClass(GreedLand.class);
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        EnterpriseProject enterpriseProject = (EnterpriseProject) SecurityUtils.getSubject().getSession().getAttribute("area");
        criteria.add(Restrictions.eq("departid", sysUser.getProId().toString()));
        criteria.add(Restrictions.eq("areaid", enterpriseProject.getId().toString()));
        criteria.add(Restrictions.eq("state",0));
        List<GreedLand> list = greedlandService.findByConditions(criteria);
        return Layui.data(0, "查询成功", list);
    }
        /**
         * 选择问题接收方
        * */
    @ResponseBody
    @RequestMapping(value = "select")
    public Layui sec(@RequestParam(value = "greenid",required = false)Integer greenid) {
        DetachedCriteria criteria = DetachedCriteria.forClass(SysUser.class);
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getSession().getAttribute("om_user");
        EnterpriseProject enterpriseProject = (EnterpriseProject) SecurityUtils.getSubject().getSession().getAttribute("area");
        criteria.createAlias("sysRole.sysRoleCode","code");
        criteria.add(Restrictions.eq("enterprise", sysUser.getEnterprise()));
        criteria.add(Restrictions.eq("areaid", enterpriseProject.getId()));
        criteria.add(Restrictions.eq("code.role_number","construction"));
        List<SysUser> userlist = new ArrayList<>();
        List<SysUser> list = openAccountService.findByConditions(criteria);
        for (SysUser user : list) {
            String[] split = user.getGreenlandid().split(",");
            for (int i = 0; i < split.length; i++) {
                if (Integer.parseInt(split[i])==greenid){
                    userlist.add(user);
                }
            }
        }
        return Layui.data(0, "查询成功", userlist);
    }
}
